package com.ltxtiyu.video.consumer;

import com.alibaba.fastjson.JSON;
import com.ltxtiyu.video.common.ConfigConstant;
import com.ltxtiyu.video.dao.ltx.MomentCountDao;
import com.ltxtiyu.video.dao.ltx.MomentUserPlayDao;
import com.ltxtiyu.video.entity.MomentCount;
import com.ltxtiyu.video.entity.MomentUserPlay;
import com.ltxtiyu.video.tool.StringTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 关于moment的consumer
 *
 */
@Component
public class MomentMessageConsumer {
    public static final Logger LOGGER = LoggerFactory.getLogger(MomentMessageConsumer.class);

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MomentCountDao momentCountDao;
    @Autowired
    MomentUserPlayDao momentUserPlayDao;

    /**
     * 同步redis的moment的统计参数的数据到数据库的consumer
     * 请严格遵守map的参数名和类型
     * @param map
     */
    @RabbitListener(queues=ConfigConstant.MESSAGE_NAME_MOMENT_REFRESH_WRITE)
    public void momentRefreshWriteMessage(Map<String,Object> map){
        Integer momentId = Integer.parseInt(String.valueOf(map.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_MOMENT)));
        Integer likeCount = Integer.parseInt(String.valueOf(map.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_LIKE_NOW)));
        Integer viewCount = Integer.parseInt(String.valueOf(map.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW_NOW)));
        Integer shareCount = Integer.parseInt(String.valueOf(map.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_SHARE_NOW)));
        Integer commentCount = Integer.parseInt(String.valueOf(map.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT_NOW)));
        try {
            MomentCount momentCount = momentCountDao.selectByMomentId(momentId);
            if(momentCount != null){     // 就算被封视频也同步数据
                momentCount.setCountLike(likeCount);
                momentCount.setCountView(viewCount);
                momentCount.setCountShare(shareCount);
                momentCount.setCountComment(commentCount);
                momentCountDao.updateByPrimaryKeySelective(momentCount);
                LOGGER.info(">>>>>>>>>>>>>>>>redis同步数据成功! momentId:{}", momentId);
            }
        } catch (Exception e) {
            LOGGER.info(">>>>>>>>>>>>>>>>redis同步数据失败! momentId:{}", momentId);
            e.printStackTrace();
        }finally {  // 无论如何都将redis里的数据修改状态为1, 以便下次操作
            // 修改redis的缓存老数据 保持一致
            map.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_LIKE,likeCount+"");
            map.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW,viewCount+"");
            map.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_SHARE,shareCount+"");
            map.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT,commentCount+"");
            map.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_FLAG, 1+"");
            stringRedisTemplate.opsForHash().put(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, momentId + "", JSON.toJSONString(map));
        }
    }

    /**
     * 添加视频完播次数记录
     * @param map
     */
    @RabbitListener(queues=ConfigConstant.MESSAGE_NAME_MOMENT_ADD_PLAY_TIMES)
    public void momentAddPlayTimesMessage(Map<String,Object> map){
        try{
            Object userId = map.get("user_id");
            if(userId != null){
                Map<String, Object> params = new HashMap<>();
                params.put("userId", (Integer)userId);
                params.put("momentId",(Integer)map.get("moment_id"));
                MomentUserPlay momentUserPlay =  momentUserPlayDao.selectOneByParams(params);
                if(momentUserPlay == null){
                    momentUserPlay = new MomentUserPlay();
                    momentUserPlay.setUserId((Integer)userId);
                    momentUserPlay.setMomentId((Integer)map.get("moment_id"));
                    momentUserPlay.setFullPalyTimes((Integer)map.get("full_play_times"));
                    momentUserPlay.setPlayTime(StringTool.stringToDate(String.valueOf(map.get("play_date"))));
                    momentUserPlayDao.insertSelective(momentUserPlay);
                }else {     // 更新 增加播放次数
                    momentUserPlay.setPlayTime(StringTool.stringToDate(String.valueOf(map.get("play_date"))));
                    momentUserPlay.setFullPalyTimes(momentUserPlay.getFullPalyTimes().intValue() + (int)map.get("full_play_times"));
                    momentUserPlayDao.updateByPrimaryKeySelective(momentUserPlay);
                }
            }
        }catch (Exception e){
            LOGGER.error(">>>>>>>>>>>>>添加视频完播单个记录出错, 参数:{}, 错误信息:{}",map.toString(),e);
        }
    }

}
